<?php

namespace app\controllers;

use app\award\Profit;
use app\commission\CommissionNew;
use app\models\MonthBox;
use app\models\MonthBoxYear;
use app\models\MonthProfit;
use app\models\order\Order;
use app\models\Queue;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;

class QueueController extends Controller
{
    /*
     * 0 1 1 * * command           #每月1号凌晨1点执行一次
     *
     * 每月1号2:30执行
     * 30 2 1 * * /usr/bin/curl http://www3.fanghua888.icu/queue/index
     *
     * 用现就这个处理 复购补贴
     */
    public function actionIndex()
    {
        set_time_limit(60 * 60 * 24);

        $has = MonthBox::find()
            ->where(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
            // 已返的
            ->andWhere(['status' => 1])
            ->one();
        if ($has) {
            return '本月已分过红了...';
        }

        // 先删除未返佣的, 重新计算上个月的
        MonthBox::deleteAll(['status' => 0]);

        $list = Profit::getListFinal();

        foreach ($list as $item) {
            if ($item['amount_1'] + $item['amount_2'] + $item['amount_3'] + $item['amount_4'] > 0) {
                $this->saveCommission($item, 101, '补贴', 1, 1);
                echo '会员: ', $item['id'], " 完成\n";
            }


        }

        echo '处理完毕.........';

    }

    // 这个是车房用
    public function actionYear()
    {
        set_time_limit(60 * 60 * 24);

        $has = MonthBoxYear::find()
            ->where(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
            // 已返的
            ->andWhere(['status' => 1])
            ->one();
        if ($has) {
            return '本月已分过红了...';
        }

        // 先删除未返佣的, 重新计算上个月的
        MonthBoxYear::deleteAll(['status' => 0]);

        $list = Profit::getListFinal();

        foreach ($list as $item) {
            if ($item['box'] == 0) {
                continue;
            }

            $amount1 = 0;
            $amount2 = 0;

            if ($item['box'] >= 7000) {
                $amount1 = 30000;
            }
            if ($item['box'] >= 13000) {
                $amount1 = 60000;
            }

            if ($item['box'] >= 50000) {
                $amount2 = 200000;
            }
            if ($item['box'] >= 100000) {
                $amount2 = 500000;
            }

            if ($amount1 + $amount2 == 0) {
                continue;
            }

            $log = new MonthBoxYear();
            $log->user_id = $item['id'];
            $log->box = $item['box'];
            $log->amount_1 = $amount1;
            $log->amount_2 = $amount2;
            $log->status = 1;
            $log->save();

            echo '会员: ', $item['id'], " 完成\n";

        }

        echo '处理完毕.........';

    }




    public function actionIndex2()
    {
        set_time_limit(60 * 60 * 24);

        $type = 202;
        $name = '月奖';

        $has = MonthProfit::find()
            ->where(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
            ->andWhere(['type' => 2])
            ->one();
        if ($has) {
            return '已分过红了...';
        }

        $list = Profit::getList(2);
        // var_dump($list);exit;

        foreach ($list as $item) {
            if ($item['real_amount'] == 0) {
                continue;
            }

            $this->saveCommission($item, $type, $name, 1, 2);
            echo '佣金: ', $item['id'], ' , 金额: ', $item['real_amount'], "\n";
        }

        echo '处理完毕.........';

    }

    // 分红
    public function actionIndex3()
    {
        // 这个限制一定要加的
        $has = UserCommission::find()
            ->where(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
            ->andWhere(['award_type' => 210])
            ->one();
        if ($has) {
            return '本月已分过红了...';
        }

        $type = 210;
        $name = '分红';

        $total = (float) Order::find()
            ->andWhere(['is_extract' => 0])
            // 上个月
            ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            ->andWhere(['is_repeat' => 0])
            ->sum('total_price');

        $set = SetUserUp::getLastOne();
        $c3 = $set->p3 * $total / 100;
        $c4 = $set->p4 * $total / 100;
        $c5 = $set->p5 * $total / 100;

        $vip3 = User::find()
            ->where(['level' => UserLevel::$keys['vip3']])
            ->all();
        foreach ($vip3 as $user) {
            $c = $c3 / count($vip3);
            $this->saveCommission2($user->id, $c, $type, $name);
            echo '佣金: ', $user->id, ' , 金额: ', $c, "\n";
        }
        $vip4 = User::find()
            ->where(['level' => UserLevel::$keys['vip4']])
            ->all();
        foreach ($vip4 as $user) {
            $c = $c4 / count($vip4);
            $this->saveCommission2($user->id, $c, $type, $name);
            echo '佣金: ', $user->id, ' , 金额: ', $c, "\n";
        }
        $vip5 = User::find()
            ->where(['level' => UserLevel::$keys['vip5']])
            ->all();
        foreach ($vip5 as $user) {
            $c = $c5 / count($vip5);
            $this->saveCommission2($user->id, $c, $type, $name);
            echo '佣金: ', $user->id, ' , 金额: ', $c, "\n";
        }

    }

    // 保存佣金
    protected function saveCommission($item, $type, $name, $status = 1, $m = 1)
    {
        $user_id = $item['id'];
        $balance = $item['amount_1'] + $item['amount_2'] + $item['amount_3'] + $item['amount_4'];

        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = 0;
            $model->order_id = 0;
            $model->balance = $balance;
            $model->status = $status;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                if ($status == 1) {
                    $account->balance += $balance;
                    $account->save();
                } else {
                    $account->await_balance += $balance;
                    $account->save();
                }
            }

            // 记录数量
            // $log = new MonthProfit();
            // $log->user_id = $user_id;
            // $log->amount = $item['total'];  // 总数量
            // $log->ratio = $item['ratio'];   // 单价
            // $log->all_commission = $item['amount']; // 全部佣金
            // $log->real_commission = $item['real_amount'];  // 真实佣金
            // $log->type = $m;
            // $log->save();

            $log = new MonthBox();
            $log->user_id = $user_id;
            $log->team_box = $item['team_box'];
            $log->box = $item['box'];
            $log->team_amount_1 = $item['team_amount_1'];
            $log->team_amount_2 = $item['team_amount_2'];
            $log->team_amount_3 = $item['team_amount_3'];
            $log->team_amount_4 = $item['team_amount_4'];
            $log->amount_1 = $item['amount_1'];
            $log->amount_2 = $item['amount_2'];
            $log->amount_3 = $item['amount_3'];
            $log->amount_4 = $item['amount_4'];

            // 记录返佣状态
            $log->status = 1;

            $log->save();
        }
    }

    protected function saveCommission2($user_id, $balance, $type, $name, $status = 1)
    {
        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = 0;
            $model->order_id = 0;
            $model->balance = $balance;
            $model->status = $status;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                if ($status == 1) {
                    $account->balance += $balance;
                    $account->save();
                } else {
                    $account->await_balance += $balance;
                    $account->save();
                }
            }
        }
    }


    // */5 * * * * /usr/bin/curl https://api.wochuang8.top/queue/index
    // public function actionIndex()
    // {
    //     $list = Queue::find()
    //         ->where(['status' => 0])
    //         ->orderBy(['id' => SORT_ASC])
    //         ->limit(30)
    //         ->all();
    //
    //     if (empty($list)) {
    //         return '[ 已经全部完成 ]';
    //     }
    //
    //     foreach ($list as $item) {
    //         // 处理奖项
    //         $order = Order::findOne(['id' => $item->order_id]);
    //         if ($order) {
    //             $c = new CommissionNew($order, true);
    //             $c->receive_performance();
    //         }
    //
    //         $item->status = 1;
    //         $item->save();
    //     }
    //
    //     return ' [ 操作完成 ]';
    //
    // }
}